<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/10
 * Time: 11:22
 */

namespace app\applet\model;


use think\Db;

class Express
{
    private $key = "aVdPEylr1606";#客户授权key
    private $customer = 'CCA7FF6A8DC713B70733C81BA38B2C00';	#查询公司编号
    #查询物流公司
    public function expressCompany()
    {
        $data = Db::name("express_company")
            ->field("id,name,code")
            ->order(["id"=>'asc'])
            ->select();
            return $data;

    }
    #查询快递状态
    public function queryExpress($num)
    {
        $address = Db::name("order")
            ->field("address")
            ->where(['log_sn'=>$num['num'],'log_id'=>$num['id']])
            ->find();
        if($address)
        {
            $address = $address['address'];
        }else{
            $address = "缺省地址";
        }
        $code = Db::name("express_company")
            ->field("name,code")
            ->where(['id'=>$num['id']])
            ->find();
        #订单号
        $data['num'] = $num['num'];
        $data['com'] = $code['code'];
        #快递公司编号,需要从数据库根据单号获取

        $post_data = array();
        $post_data["customer"] = $this->customer;
        $post_data["param"] = json_encode($data);
        $sign = md5($post_data["param"].$this->key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);
        $url = 'http://poll.kuaidi100.com/poll/query.do';	//实时查询请求地址
        $data = "";
        foreach ($post_data as $k=>$v) {
            $data .= "$k=".urlencode($v)."&";		//默认UTF-8编码格式
        }
        #请求参数
        $post_data = substr($data, 0, -1);

        #发送post请求
        $data = self::curlPost($url,$post_data);
        if(!empty($data['nu']) && $data['nu']==$num['num'])
        {
            $return_data['state'] = $data['state'];
            $return_data['address'] = $address;
            $return_data['name'] = $code['name'];
            $return_data['info']  = $data['data'];
            return $return_data;
        }else{
            returnJson(-2004,"网络繁忙,请稍后请求");
        }





    }
    #curl请求
    private function curlPost($url,$post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data = str_replace("\"", '"', $result );
        $data = json_decode($data,true);
        return $data;
    }

}